import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import store, { STORE_KEY } from '@store';
import { KEY } from '@utils/config';
/* Layout */
import Layout from '../layout/index.vue';

export const constantRoutes = [
    {
        path: '/',
        redirect: '/transfer',
    },
    {
        path: '/redirect',
        component: Layout,
        hidden: true,
        children: [
            {
                path: '/redirect/:path(.*)',
                component: () => import('../views/redirect'),
            },
        ],
    },
    {
        path: '/transfer',
        hidden: true,
        component: () => import('@views/transfer/index.vue'),
    },
    {
        path: '/login',
        hidden: true,
        component: () => import('@views/login/index.vue'),
    },
    // {
    //     path: '/dashboard',
    //     hidden: false,
    //     component: Layout,
    //     meta: { title: '概况', icon: 'Fold' },
    //     children: [
    //         {
    //             path: '',
    //             component: () => import('@views/dashboard/index.vue'),
    //             name: 'dashboard',
    //             meta: { title: '概况', icon: 'Fold', affix: false },
    //         },
    //     ],
    // },
    // {
    //     path: '/setting',
    //     hidden: false,
    //     component: Layout,
    //     meta: { title: '系统设置', icon: 'Setting' },
    //     children: [
    //         {
    //             path: 'sysDict/list',
    //             component: () => import('@views/config_direct/index.vue'),
    //             hidden: false,
    //             name: 'sys_direct_list',
    //             meta: { title: '字典配置', icon: 'Fold', affix: false },
    //         },
    //         {
    //             path: 'doLog/list',
    //             component: () => import('@views/doLog/index.vue'),
    //             hidden: false,
    //             name: 'sys_direct2_list',
    //             meta: { title: '操作日志', icon: 'Fold', affix: false },
    //         },
    //         {
    //             path: 'loginLog/list',
    //             component: () => import('@views/loginLog/index.vue'),
    //             hidden: false,
    //             name: 'sys_direct3_list',
    //             meta: { title: '登陆日志', icon: 'Fold', affix: false },
    //         },
    //     ],
    // },
    // {
    //     path: '/framework',
    //     hidden: false,
    //     component: Layout,
    //     name: 'framework',
    //     meta: { title: '组织架构', icon: 'Aim', breadcrumb: false },
    //     children: [
    //         {
    //             path: 'organizational/management',
    //             component: () => import('@views/organizational/index.vue'),
    //             hidden: false,
    //             name: 'TXZ_organizational',
    //             meta: { title: '机构管理', keepAlive: true },
    //         },
    //         {
    //             path: 'position/management',
    //             component: () => import('@views/position/index.vue'),
    //             hidden: false,
    //             name: 'TXZ_position',
    //             meta: { title: '机构组别', keepAlive: false },
    //             props: true
    //         },
    //     ],
    // },
    // {
    //     path: '/auth',
    //     hidden: false,
    //     component: Layout,
    //     meta: { title: '权限管理', icon: 'Aim' },
    //     children: [
    //         {
    //             path: 'sysConfig/list',
    //             component: () => import('@views/config_argument/index.vue'),
    //             hidden: false,
    //             name: 'sys_direct2_list',
    //             meta: { title: '参数配置', affix: false },
    //         },
    //         {
    //             path: 'sysUser/list',
    //             component: () => import('@views/user/index.vue'),
    //             hidden: false,
    //             name: 'sys_user_list',
    //             meta: { title: '账号管理', affix: false },
    //         },
    //         {
    //             path: 'sysMenu/list',
    //             component: () => import('@views/menu/index.vue'),
    //             hidden: false,
    //             name: 'sys_menu_list',
    //             meta: { title: '菜单管理', affix: false },
    //         },
    //         {
    //             path: 'sysRole/list',
    //             component: () => import('@views/role/index.vue'),
    //             hidden: false,
    //             name: 'TXZ_role',
    //             meta: { title: '角色配置', keepAlive: true },
    //         },
    //     ],
    // },
    {
        path: '/404', // /:pathMatch(.*)'
        name: 'page-not-found',
        hidden: true,
        component: Layout,
        children: [
            {
                path: '',
                component: () => import('@views/404/index.vue'),
                name: '404',
                meta: { title: '404', icon: 'Fold', affix: false },
            },
        ],
    },
    {
        path: '/:pathMatch(.*)',
        redirect: '/404',
    },
];

const modules = import.meta.glob('./../views/**/index.vue');
const modulesMap = {};
for (let x in modules) {
    let ta = x.match(/.\/..\/views(\S*)\/index.vue/)[1];
    modulesMap[ta] = modules[x];
}

//下面都是动态路由
export const initRoutes = routeList => {
    let mainRoute = []; //主路由，左边nav
    let buttonMap = {}; //按钮权限
    routeList.forEach(item => {
        handleRoute(mainRoute, buttonMap, item);
        store.commit(STORE_KEY.M_UPDATE_MAIN_ROUTES, mainRoute);
    });
    // store.commit(STORE_KEY.M_UPDATE_BTN_PREMISSION, buttonMap)
};

const handleRoute = (routes, buttonMap, item) => {
    if (!item.path) return;
    let route = null;

    if (item.children && item.children.length > 0) {
        item.children = item.children.filter(childItem => {
            let viewName = '/' + getComponent(childItem.path);
            return !!modulesMap[viewName];
        });
    }
    if (item.children && item.children.length > 0) {
        //一级路由
        route = {
            path: item.path,
            name: item.name,
            component: Layout,
            hidden: !item.visible,
            meta: {
                icon: getIcon(item.icon),
                title: item.name,
                breadcrumb: false,
            },
        };
        router.addRoute(route);

        route.children = [];

        for (let i = 0; i < item.children.length; i++) {
            let childItem = item.children[i];
            let viewName = getComponent(childItem.path);
            let viewName2 = '/' + viewName;
            if (!modulesMap[viewName2]) continue;
            let subRoute = {
                path: childItem.path,
                component: modulesMap[viewName2], //此处加载对应的模板
                name: KEY + '_' + viewName,
                hidden: !childItem.visible ? !childItem.visible : isHidden(viewName),
                meta: {
                    // title: item.children.length === 1 ? item.name : childItem.name,
                    title: childItem.name,
                    keepAlive: true,
                },
            };
            
            route.children.push(subRoute);
            if (!childItem.path.includes('http') && !childItem.path.includes('method_')) {
                router.addRoute(route.name, subRoute);
            }
        }
    } else {
        let viewName = getComponent(item.name);
        let viewName2 = '/' + viewName;
        if (modulesMap[viewName2]) {
            route = {
                path: item.path,
                component: Layout,
                hidden: !item.visible,
                children: [
                    {
                        path: '',
                        component: modulesMap[viewName2],
                        name: KEY + '_P_' + item.name,
                        meta: {
                            title: item.name,
                            icon: getIcon(item.icon),
                        },
                    },
                ],
            };
            router.addRoute(route);
        }
    }
    route && routes.push(route);
};

const router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes,
    scrollBehavior: () => ({ top: 0 }),
});

export default router;

const getComponent = key => {
    return componentMap[key] || key;
};

const componentMap = {
    'financialData/list': 'financial_data',
    'flowFunds/list': 'flow_funds',
    'drainage/list': 'drainage_statements',
    'consumer/list': 'consumer_statements',
    'franchisee/list': 'franchisee_statements',
    'sysConfig/list': 'config_argument',
    'sysDirect/list': 'config_direct',
    'threeConfig/list': 'threeConfig',

    'job/pageQuery': 'schedule',
    'sysLog/list': 'log',
    'sysMonitor/list': 'sys_monitor',

    'sysCompany/list': 'company',
    'sysDepart/list': 'dept',
    'sysMenu/list': 'menu',
    'sysStation/list': 'station',
    'sysRole/list': 'role',
    'sysGroup/list': 'group',
    'sysUser/list': 'user',
    'leasePeriodSwitch/list': 'leasePeriodSwitch',

    'riskAccount/list': 'risk_account',
    'bfqzPay/edit': 'bill_info',
    'bfqzCategory/list': 'goods_category',
    'bfqzGoods/list': 'goods',
    'bfqzUser/list': 'bfqz_user',
    'bfqzPlatform/edit': 'platform_manage',
    'bfqzSuggestions/list': 'suggestion',
    'bfqzOrder/list': 'order',
    'bfqzOrderOverdue/list': 'orderOverdue',
    'bfqzCoupon/list': 'coupon',
    'bfqzHome/list': 'home_activity',

    'merchant/balance': 'merchant_balance',
    'riskControl/balance': 'riskControl_balance',
    'withdraw/apply': 'withdraw_apply',
    'withdraw/record': 'withdraw_record',
    'doLog/list': 'doLog',
    'loginLog/list': 'loginLog',
    'organizational/management': 'organizational',
    'position/management': 'position',
    'channelManag/list': 'channelManag',
    'channelStat/list': 'channelStat',
};

const getIcon = key => {
    return iconMap[key] || key;
};

const iconMap = {
    user: 'User',
};

const isHidden = viewName => {
    return hiddenMap[viewName] || false;
};

const hiddenMap = {
    order_mall_detail: true,
};
